import services from '@/services/demo';
import {
  ActionType,
  FooterToolbar,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Drawer, message,Form,Modal } from 'antd';
import React, { useRef, useState,useEffect } from 'react';
import CreateForm from '@/components/CreateForm';
import { history } from 'umi';

const { noticeList,noticeAdd,noticeUpdate,noticeDelete } =
  services.UserController;

const TableList: React.FC<unknown> = () => {
  const [list, setList] = useState<any[]>([]);// 列表数据
  const [pageNum, setPageNum] = useState<number>(1);// 页码
  const [actionId, setActionId] = useState<string>('');// 
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const columns: ProDescriptionsItemProps<API.UserInfo>[] = [
    {
      title: '标题',
      dataIndex: 'title',
      // tip: '名称是唯一的 key',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '标题为必填项',
          },
        ],
      },
    },
    {
      title: '内容',
      dataIndex: 'text',
      hideInSearch:true,
      valueType: 'textarea',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '内容为必填项',
          },
        ],
      },
    },
    {
      title: '发布者',
      dataIndex: 'publisher',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '发布者为必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleRemove(record.id || '')
            }}
          >
            删除
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => add(record)}
          >
            编辑
          </a> 
        </>
      ),
    },
  ];
  // 获取列表数据
  const getList = ()=>{
    noticeList({pageNum,pageSize:10,...searchData}).then((res:any)=>{
      if(res.code=='200'){
        setList(res.data.list || [])
        setTotal(res.data.total)
      }else if(res.code=='401'){
        message.error(res.message);
        history.push('/login');
      }else{
        message.error(res.message);
      }
    })
  }
  const [searchData, setSearchData] = useState<any>({});// 搜索参数
  useEffect(()=>{
    getList()// 获取列表数据
  },[pageNum,searchData])
  // const searchData=
  const search = async (value:any) => {
    console.log('search',value)
    setPageNum(1)
    setSearchData({...value})
  }
  const add = (data:any={})=>{
    form.resetFields();// 重置
    handleModalVisible(true)
    if(data.id){// 编辑  
      setActionId(data.id || '')
      form.setFieldsValue({...data})
    }else{// 新建
      setActionId('')
    }
  }
  const onsubmit = async (value:any) => {
    if(actionId){
      noticeUpdate({id:actionId,...value}).then((res:any)=>{
        if(res.code=='200'){
          message.success('修改成功');
          handleModalVisible(false)
          getList()
        }else{
          message.error(res.message);
        }
      })
    }else{
      noticeAdd({...value}).then((res:any)=>{
        if(res.code=='200'){
          message.success('提交成功');
          handleModalVisible(false)
          getList()
        }else{
          message.error(res.message);
        }
      })
    }
  }
  // 删除节点
  const handleRemove = async (id:string) => {
    Modal.confirm({
      title: '确定删除此条数据？',
      content: '',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        const hide = message.loading('正在删除');
        noticeDelete({id:id}).then((res:any)=>{
          if(res.code=='200'){
            message.success('删除成功，即将刷新');
            getList()
          }else{
            message.error(res.message);
          }
          hide()
        })
        // hide()
      },
      onCancel() {
        
      },
    });
  };
  const [total, setTotal] = useState<number>(0);// 总数
  const pageOnChange = (page:number, pageSize:number)=>{
    setPageNum(page)
  }
  return (
    <div>
      <ProTable<API.UserInfo>
        // headerTitle="查询表格"
        actionRef={actionRef}
        onSubmit={search}
        rowKey="id"
        search={{
          defaultCollapsed:false,
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => add()}
          >
            新建
          </Button>,
        ]}
        pagination={{
          total,
          current:pageNum,
          pageSizeOptions:[],
          pageSize:10,
          hideOnSinglePage:true,
          onChange:pageOnChange
        }}
        dataSource={list}
        columns={columns}
      />
      <CreateForm
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        title={actionId?'编辑':'新增'}
      >
        <ProTable<API.UserInfo, API.UserInfo>
          onSubmit={onsubmit}
          rowKey="id"
          type="form"
          form={{
            form,
          }}
          columns={columns}
        />
      </CreateForm>
    </div>
  );
};

export default TableList;
